package com.hezuti.sns.action;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.hezuti.common.action.BaseAction;
import com.hezuti.common.utils.CookieUtil;
import com.hezuti.sns.domain.Lserial;
import com.hezuti.sns.domain.User;
import com.hezuti.sns.service.UserService;

@SuppressWarnings("serial")
public class SnsAction extends BaseAction{
	
	protected User user;
	
	private String id;
	
	@Autowired
	protected UserService userService;
	
	protected void setUserInfo(User u){
		getSession().setAttribute(""+u.getId(), u);
	}
	
	public User getUserInfo(){
		//TODO 将来，对cookie 进行加密；
		String uid = CookieUtil.getValueFromCookies(getRequest(), "id");
		if(uid!=null){
		Object o=getSession().getAttribute(uid);
		if(null!=o){
			user=(User)o;
		}else{
				user = userService.getUserById(uid);
			if(null!=user){
				id=user.getId()+"";
				Cookie cookie=new Cookie("id",id);
				cookie.setPath("/");
				CookieUtil.writeCookie(getResponse(), cookie);
				getSession().setAttribute(id, user);
			}
		}
		}
		return user;
	}
	public Lserial loginUser(int type){
		if(null!=user){
			id=user.getId()+"";
			Cookie cookie=new Cookie("id",id);
			cookie.setPath("/");
			CookieUtil.writeCookie(getResponse(), cookie);
			getSession().setAttribute(id, user);
			return userService.doRecLoginOpreate(user.getId(), getIp(),type);
		}
		return null;
	}
	public void logoutUser(){
		String id=CookieUtil.getValueFromCookies(getRequest(), "id");
		if(null!=id&&!"".equals(id)){
			getSession().removeAttribute(id);
		}
	}
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public User getUser() {
		return user;
	}
	
	/**
	 * str为空 返回 true 否则返回false
	 * 
	 * @param str
	 * @return
	 */
	protected boolean isNull(String str){
		if(null==str)
			return true;
		if("".equals(str.trim()))
			return true;
		return false;
	}
}
